from django.shortcuts import render, get_object_or_404, redirect, reverse
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.db.models import Q
from .models import Post, Category, Tag, Comment
from .forms import PostForm, CommentForm
from django.views.decorators.http import require_POST
import markdown


class PostListView(ListView):
    model = Post
    template_name = 'home.html'  # 更新为您的模板路径
    context_object_name = 'posts'
    paginate_by = 6

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['categories'] = Category.objects.all()
        context['tags'] = Tag.objects.all()
        context['popular_posts'] = Post.objects.order_by('-views')[:5]
        return context

    def get_queryset(self):
        queryset = super().get_queryset()
        category_id = self.request.GET.get('category')
        tag_id = self.request.GET.get('tag')
        search_query = self.request.GET.get('search')

        if category_id:
            queryset = queryset.filter(category_id=category_id)
        if tag_id:
            queryset = queryset.filter(tags=tag_id)
        if search_query:
            queryset = queryset.filter(
                Q(title__icontains=search_query) |
                Q(content__icontains=search_query) |
                Q(excerpt__icontains=search_query)
            )
        return queryset.order_by('-created_at')


class PostDetailView(DetailView):
    model = Post
    template_name = 'article_details.html'  # 更新为您的模板路径
    context_object_name = 'post'

    def get_object(self, queryset=None):
        post = super().get_object(queryset)
        post.increase_views()
        # 将Markdown内容转换为HTML
        post.content = markdown.markdown(post.content, extensions=[
            'markdown.extensions.extra',
            'markdown.extensions.codehilite',
        ])
        return post

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['comment_form'] = CommentForm()
        context['comments'] = self.object.comments.filter(parent=None).order_by('-created_at')
        context['popular_posts'] = Post.objects.order_by('-views')[:5]
        return context


class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    form_class = PostForm
    template_name = 'post_create.html'  # 需要在templates目录下创建

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)


class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Post
    form_class = PostForm
    template_name = 'post_update.html'  # 需要在templates目录下创建

    def test_func(self):
        post = self.get_object()
        return self.request.user == post.author


class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    model = Post
    template_name = 'post_delete.html'  # 需要在templates目录下创建
    success_url = '/'

    def test_func(self):
        post = self.get_object()
        return self.request.user == post.author


@login_required
@require_POST
def post_comment(request, post_pk):
    post = get_object_or_404(Post, pk=post_pk)
    form = CommentForm(request.POST)

    if form.is_valid():
        comment = form.save(commit=False)
        comment.author = request.user
        comment.post = post
        comment.save()
        return HttpResponseRedirect(post.get_absolute_url())

    context = {
        'post': post,
        'form': form,
        'comments': post.comments.filter(parent=None).order_by('-created_at'),
    }
    return render(request, 'article_details.html', context)


def category_posts(request, category_slug):
    category = get_object_or_404(Category, name=category_slug)
    posts = Post.objects.filter(category=category).order_by('-created_at')
    return render(request, 'category.html', {
        'category': category,
        'posts': posts,
        'categories': Category.objects.all(),
        'tags': Tag.objects.all(),
    })


def tag_posts(request, tag_slug):
    tag = get_object_or_404(Tag, name=tag_slug)
    posts = Post.objects.filter(tags=tag).order_by('-created_at')
    return render(request, 'tag.html', {
        'tag': tag,
        'posts': posts,
        'categories': Category.objects.all(),
        'tags': Tag.objects.all(),
    })